#include <muduo/net/TcpServer.h>
#include <muduo/net/EventLoop.h>
#include <iostream>
#include <string>
#include <time.h>

class EchoServer
{
public:
    EchoServer(muduo::net::EventLoop *ep,const muduo::net::InetAddress &listenAddr)
        :_server(ep,listenAddr,"EchoServer")
    {
        _server.setConnectionCallback(std::bind(&EchoServer::connection_handler,this,std::placeholders::_1));// 连接建立，要做啥？
        _server.setMessageCallback(std::bind(&EchoServer::message_handler,this,
        std::placeholders::_1,std::placeholders::_2,std::placeholders::_3));// 有消息到来，要做啥?

        _server.start();
    }

    void connection_handler(const muduo::net::TcpConnectionPtr &conn)// 连接到了，muduo自动将连接传递给回调
    {
        std::cout << "新连接已到!" << conn->peerAddress().toIpPort() << " " 
        << conn->localAddress().toIpPort() << std::endl;
        // if(conn->connected())
        // {
        //     conn->send(muduo::Timestamp::now().toFormattedString() + "\n");
        //     conn->shutdown();
        // }

        if(conn->connected())
        {
            time_t tm = time(nullptr);// 获取现在的时间
            int32_t be = muduo::net::sockets::hostToNetwork32(static_cast<int32_t>(tm));
            conn->send(&be,sizeof(be));
            conn->shutdown();
        }
    }

    // 接收到消息的回调函数，参数由muduo自行设置：发送消息的连接、消息是什么(消息在缓冲区的位置)、收到消息的时间
    void message_handler(const muduo::net::TcpConnectionPtr &conn,muduo::net::Buffer *buf,muduo::Timestamp time)
    {
        std::string msg(buf->retrieveAllAsString());
        std::cout << conn->name() << " " << msg.size() << "bytes" << " " 
        << "接收到消息: " << msg << " 时间: " << time.toString() << std::endl;
        conn->send(msg);
    }
    muduo::net::TcpServer _server;
};
int main()
{
    muduo::net::EventLoop ep;
    muduo::net::InetAddress addr(9090);
    EchoServer server(&ep,addr);
    ep.loop();
    return 0;
}

